#include <config.h>
#include <core.h>

int   log_daemon_flags;
char *log_colores[] = {FATAL_COLOR,ERROR_COLOR,WARNING_COLOR,INFO_COLOR,DEBUG_COLOR,FINE_COLOR,FINEST_COLOR,NORMAL_COLOR};
char *log_level_str[] = {"FATAL","ERROR","WARN","INFO","DEBUG","FINE","FINEST"};
int   log_fd    = STDOUT_FILENO;
int   log_level = LOGL_INFO; 

void set_log_level(int level)
{
      log_level = level;
}

void set_log_fd(int fd)
{
      log_fd = fd;
}

void log_doit(int errflags,const char * fileName, uint32_t lineNumber,
                  const char * functionName , int level,const char *fmt,...)
{
    if(log_level < level ) return ;

    va_list ap;
    int saveerrno , n;  
    char buf[ERR_MAX_LINE];     
    saveerrno = errno; 
    
    memset(buf,0,ERR_MAX_LINE);

    time_t st = time(NULL);
    struct tm *tm = localtime(&st);
    snprintf(buf,sizeof(buf),"[%02d-%02d %02d:%02d:%02d]%s:%"PRIu32"(%s[%d#%ld])[%s] ",
                 tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec,fileName,lineNumber,functionName,getpid(),pthread_self(),log_level_str[level]); 

    n = strlen(buf);
    va_start(ap,fmt);
    #ifdef HAVE_VSNPRINTF
	vsnprintf(buf+n,sizeof(buf)-n,fmt,ap);
    #else
        vsprintf(buf+n,fmt,ap);
    #endif
    va_end(ap);

    n = strlen(buf);

    if(errflags && saveerrno){
         snprintf(buf+n,sizeof(buf)-n,", %d:%s",errno,strerror(saveerrno));
         errno = 0;
    }
    strcat(buf,"\n");

    if(log_daemon_flags){
	syslog(level,buf);
    }else{  
        if(log_fd == STDOUT_FILENO){
	  //fflush(stdout);
	  fflush(stderr);
          SET_CONSOLE_TEXT_COLOR(log_colores[level]);
          fprintf(stdout,buf);
          SET_CONSOLE_TEXT_COLOR(log_colores[7]);
	  fflush(stdout);
        }else{
          n = strlen(buf);
          int wn = -1;
          while((wn=write(log_fd,buf,n)) < n ){
              if(wn < 0 ){
                fprintf(stderr,"log write (%s) error:%s\n",buf,strerror(saveerrno));
	        fflush(stderr);
                return ;
              }
              n = n - wn;
         }
         //fdatasync(log_fd);
       }
    } 
    return; 
}
